'use client';

import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import { PhantomWalletAdapter, SolflareWalletAdapter } from '@solana/wallet-adapter-wallets';
import { clusterApiUrl } from '@solana/web3.js';
import { useMemo } from 'react';

// 导入钱包样式
import '@solana/wallet-adapter-react-ui/styles.css';

export function WalletContextProvider({ children }: { children: React.ReactNode }) {
  // 根据环境变量确定网络类型
  const network = useMemo(() => {
    const networkEnv = process.env.NEXT_PUBLIC_SOLANA_NETWORK;
    switch (networkEnv) {
      case 'mainnet-beta':
        return WalletAdapterNetwork.Mainnet;
      case 'testnet':
        return WalletAdapterNetwork.Testnet;
      case 'devnet':
      default:
        return WalletAdapterNetwork.Devnet;
    }
  }, []);
  
  // 根据环境变量选择网络端点
  const endpoint = useMemo(() => {
    // 如果设置了本地 RPC，使用本地测试网
    if (process.env.NEXT_PUBLIC_USE_LOCAL_RPC === 'true') {
      return 'http://localhost:8899';
    }
    // 优先使用自定义RPC URL
    const customRpcUrl = process.env.NEXT_PUBLIC_SOLANA_RPC_URL;
    if (customRpcUrl) {
      return customRpcUrl;
    }
    // 回退到标准集群URL
    return clusterApiUrl(network);
  }, [network]);

  // 连接配置选项 - 为生产环境优化
  const connectionConfig = useMemo(() => ({
    commitment: 'confirmed' as const,
    confirmTransactionInitialTimeout: 90000, // 增加到90秒
    disableRetryOnRateLimit: false,
    httpHeaders: {
      'Content-Type': 'application/json',
    },
    // 在生产环境中禁用WebSocket以避免连接问题
    wsEndpoint: process.env.NODE_ENV === 'production' ? undefined : undefined,
  }), []);

  console.log('Wallet Provider - Network:', network);
  console.log('Wallet Provider - Network Env:', process.env.NEXT_PUBLIC_SOLANA_NETWORK);
  console.log('Wallet Provider - Endpoint:', endpoint);
  console.log('Wallet Provider - Environment:', process.env.NODE_ENV);
  console.log('Wallet Provider - USE_LOCAL_RPC:', process.env.NEXT_PUBLIC_USE_LOCAL_RPC);

  const wallets = useMemo(
    () => [
      new PhantomWalletAdapter(),
      new SolflareWalletAdapter(),
    ].filter((wallet, index, array) => {
      // 确保每个钱包适配器的名称是唯一的
      return array.findIndex(w => w.name === wallet.name) === index;
    }),
    []
  );

  return (
    <ConnectionProvider endpoint={endpoint} config={connectionConfig}>
      <WalletProvider 
        wallets={wallets} 
        autoConnect={process.env.NEXT_PUBLIC_WALLET_AUTO_CONNECT === 'true'}
      >
        <WalletModalProvider>
          {children}
        </WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  );
}
